package org.streets.wicket.markup.tree;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import org.apache.wicket.IClusterable;
import org.apache.wicket.model.IDetachable;

public class DefaultCheckableState implements ICheckableState ,  IClusterable, IDetachable {

	private final Set<Object> checkedNodes = new HashSet<Object>();
	private final List<ICheckableStateListener> listeners = new ArrayList<ICheckableStateListener>(1);
	
	public void checkNode(Object node, boolean checked) {
		if (checked && !checkedNodes.contains(node)) {
			checkedNodes.add(node);
			ICheckableStateListener[] listenersCopy = listeners.toArray(new ICheckableStateListener[0]);
			for (ICheckableStateListener l : listenersCopy) {
				l.nodeChecked(node);
			}
		} else if (!checked && checkedNodes.contains(node)) {
			checkedNodes.remove(node);
			ICheckableStateListener[] listenersCopy = listeners.toArray(new ICheckableStateListener[0]);
			for (ICheckableStateListener l : listenersCopy) {
				l.nodeUncheched(node);
			}
		}		
	}

	public void addCheckableStateListener(ICheckableStateListener l) {		
		if (! listeners.contains(l)){
			listeners.add(l);
		}		
	}

	public boolean isNodeChecked(Object node) {
		
		return checkedNodes.contains(node);
	}

	public void removeCheckableStateListener(ICheckableStateListener l) {

		listeners.remove(l);		
	}

	public void detach() {
		
		for (Object node : checkedNodes)
		{
			if (node instanceof IDetachable)
			{
				((IDetachable)node).detach();
			}
		}
	}

	public Collection<Object> getCheckedNodes() {
		// TODO Auto-generated method stub
		return Collections.unmodifiableList(new ArrayList<Object>(checkedNodes));
	}
}
